require('dotenv').config();
const express = require('express');
const cors = require('cors');
const { errorHandler } = require('./middleware/error');
const { testConnection } = require('./config/db');

const app = express();

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());

// 测试数据库连接
testConnection();

// API路由
app.use('/v1/users', require('./routes/user.routes'));
app.use('/v1/categories', require('./routes/category.routes'));
app.use('/v1/products', require('./routes/product.routes'));
app.use('/v1/cart', require('./routes/cart.routes'));
app.use('/v1/orders', require('./routes/order.routes'));

// 错误处理中间件
app.use(errorHandler);

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app; 